const { ListToNode, NodeToList, ListNode, timeL } = require("../utils.js");

/**
 * 1 2 3 4 5
 * 1 2 3 5 4  12354   12435
 * 1 2 5 4 3  13245 13254
 * 4 5 3 2 1  123
 */

var nextPermutation = function (nums) {
  let arr = [];
  const fun = (list) => {
    let leng = list.length;
    for (let i = 0; i < leng; i++) {
      nums[i + nums.length - leng] = list[i];
    }
  };
  for (let i = nums.length - 1; i > 0; i--) {
    if (nums[i] > nums[i - 1]) {
      arr.push(nums[i]);
      for (let y = 0; y < arr.length; y++) {
        if (arr[y] > nums[i - 1]) {
          arr[y] += nums[i - 1];
          nums[i - 1] = arr[y] - nums[i - 1];
          arr[y] = arr[y] - nums[i - 1];
          arr = arr.sort((a, b) => a - b);
          fun(arr);
          return nums;
        }
      }
      return nums;
    } else {
      arr.push(nums[i]);
    }
  }
  arr.push(nums[0]);
  fun(arr);
  return nums;
};

let nums = [1, 3, 2];

timeL(nextPermutation, [nums]);
